<?php

namespace App\Listeners;

use App\Http\Controllers\Plugin\Models\Java\PdIntegral;
use App\Http\Controllers\Plugin\Models\Java\PdInteLog;
use App\Http\Controllers\Plugin\Models\Java\PdProduct;
use App\Models\Java\PdUserRelationship;
use App\Models\Map\Mch;
use App\Models\Map\ShopOrder;
use App\Models\Order\FailEvent;
use Illuminate\Support\Facades\DB;

class PayIntegralListener // implements ShouldQueue
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }
    // 获取产品数据
    protected function getProduct($id){
        return PdProduct::query()->find('1112'.$id);

    }
    // 获取代理商 利率
    protected function getAgentRelationShip($pid,$sid=4){
        $relationShip = PdUserRelationship::query()
            ->where('pid',$pid)
            ->where('sid',$sid)
            ->value('ratio');
        return $relationShip;
    }
    public function getShareUser($openid){
       return PdUserRelationship::query()
            ->where('role',3)
            ->where('uid',$openid)
            ->first();
    }
    // 获取当前用户等级
    protected function getUserInfo($openid,$model=-1){
        $level = DB::connection('mysql_secondary')->table('pd_level')
            ->whereRaw('pd_level.threshold >= (
              SELECT u.level
              FROM pd_user_relationship AS u
              WHERE u.uid = ?
                AND u.role = 3
              LIMIT 1
          )',[$openid])
            ->where('pd_level.mode',$model)
            ->first();
        return $level;
    }
    /**
     * Handle the event.
     *
     * @param  object  $event
     * @return void
     */
    public function handle($event)
    {
        $order = $event->order;
        $goods = $this->getProduct($order->goods_id);
        info('获取当前商品'.json_encode($goods));
        $openid = $order->openid;
        $model = $goods->account_mode;
        $user = $this->getUserInfo($openid,$model);
        info('获取当前用户'.json_encode($user));
        if($order&&$order->real_price>0){
            // 获取当前商品
            if($goods){
                if($user->is_inte_buy==1){
                    $integral = floor($order->real_price*$user->inte_scale_buy);
                    if($integral>0){
                        $data = [
                          'uid'=>$openid,
                            'name'=>$user->name,
                            'nid'=>$user->nid,
                            'inte'=>$integral,
                            'order_id'=>$order->out_trade_no,
                            'order_sid'=>$order->id,
                            'mid'=>$model,
                            'level'=>$user->level,
                            'is_over'=>2, // 待发放
                            'type'=>0
                        ];
                        $res = PdInteLog::query()->create($data);
                        if($res){
                            PdIntegral::query()->where('uid',$openid)
                                ->increment('fake_inte',$integral);
                        }
                    }
                }
                if($order->temp_openid&&$user->is_inte==1){
                    // 如果有分享和开启分享积分则
                    info('如果有分享和开启分享积分');
                    $ratio = $this->getAgentRelationShip($model);
                    if($user->is_inte==1){ // 如果给积分
                        $integral = floor($ratio*$order->real_price*$user->inte_scale);
                        $user = $this->getShareUser($order->temp_openid);
                        if($integral>0){
                            $data = [
                                'uid'=>$order->temp_openid,
                                'name'=>$user->name,
                                'nid'=>$user->nid,
                                'inte'=>$integral,
                                'order_id'=>$order->out_trade_no,
                                'order_sid'=>$order->id,
                                'mid'=>$model,
                                'level'=>$user->level,
                                'is_over'=>2, // 待发放
                                'type'=>1
                            ];
                            $res = PdInteLog::query()->create($data);
                            if($res){
                                PdIntegral::query()->where('uid',$order->temp_openid)
                                    ->increment('fake_inte',$integral);
                            }
                        }
                    }

                }
            }
//            $data = [
//                'totalAmount'=>$order->real_price,
//                'productId'=>[
//                    [
//                        'goods_id'=>'1112'.$order->goods_id,
//                        'goods_num'=>$order->quantity,
//                        'price'=>$order->real_price*$order->commission_rate,
//                        'goods_price'=>$order->real_price,
//                        'create_time'=>time(),
//                        'order_id'=>$order->out_trade_no,
//                        'share'=> $order->temp_openid??'',
//                    ]
//                ],
//                'orderId'=>$order->out_trade_no,
//                'paymentMethod'=>4,
//                'userId'=>$order->openid
//            ];
//            info('传递数据为',$data);
//            $response = Http::post(env('COMMISSION_URL').'/pay_divide/createOrders/', $data);
//            $last = $response->body();
//            info('分佣接口返回数据'.$last);
//            if($last){
//                // 事件错误日志
//                $result = json_decode($last,true);
//                if($result['code'] !== 20000){
//                    $err['id'] = $order->id;
//                    $err['order'] = $order;
//                    $err['order_table'] = $event->order_table??'shop_orders';
//                    $err['error'] = $last;
//                    FailEvent::query()->create($err);
//                }
//            }
        }
    }
}
